package com.sparrow.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

public class DataSourceTransactionManager implements TransactionManager {

	private static Map<String, TransactionManager> transactionManagerMap = new HashMap<String, TransactionManager>();

	private static TransactionManager instance = new DataSourceTransactionManager();

	public DataSourceTransactionManager() {
	};

	public static TransactionManager getInstatance() {
		instance.setDataSource(ConnectionPool.getInstance());
		return instance;
	}

	public static TransactionManager getInstatance(Enum<?> pn) {
		String poolName = pn.toString().toLowerCase();
		if (transactionManagerMap.get(poolName) != null) {
			return transactionManagerMap.get(poolName);
		} else {
			TransactionManager transactionManager = new DataSourceTransactionManager();
			transactionManager.setDataSource(ConnectionPool.getInstance(pn));
			transactionManagerMap.put(poolName, transactionManager);
			return transactionManager;
		}
	}

	private DataSource dataSource = null;
	private ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();

	@Override
	public Connection start() {
		Connection connection = null;
		try {
			connection = this.dataSource.getConnection();
			connection.setAutoCommit(false);
			this.currentConnection.set(connection);
		} catch (SQLException e) {
		}
		return connection;
	}

	@Override
	public void commit() throws SQLException {
		Connection connection = this.currentConnection.get();
		connection.commit();
		// 提交成功后释放 不成功则不释放留给rollback释放
		this.currentConnection.remove();
		connection.close();
	}

	@Override
	public void rollback() {
		Connection connection = this.currentConnection.get();
		try {
			connection.rollback();
		} catch (SQLException e) {
		} finally {
			this.currentConnection.remove();
			try {
				connection.close();
			} catch (SQLException e) {
			}
		}
	}

	@Override
	public void setDataSource(DataSource datasource) {
		this.dataSource = datasource;
	}
}
